//
//  SAAccountInfoVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/8/18.
//

#import "SAAccountInfoVC.h"
#import <AipOcrSdk/AipOcrSdk.h>
#import "SAPayRegisterDetailAPI.h"
#import "SAPayCommonUploadAPI.h"
#import "SAPayRegisterAccountInfoAPI.h"
#import "SAPayRegisterDetailModel.h"
#import "SALivingBodyCheckAPI.h"
#import "SAPayRegisterSubmitAuditAPI.h"
#import "QRCodePermissions.h"
#import "NSString+FintCommon.h"
#import "SAConsultationWechatVC.h"

@interface SAAccountInfoVC ()<HTTPAPIDelegate,UITextFieldDelegate>

@property (nonatomic, strong) UIImageView *cardImageV;
@property (nonatomic, strong) UIButton *nextBtn;

@property (nonatomic, strong) UITextField *accountNameTf;
@property (nonatomic, strong) UITextField *bankNameTf;
@property (nonatomic, strong) UITextField *bankNumTf;
@property (nonatomic, strong) SAPayRegisterDetailAPI *payRegisterDetailAPI;
@property (nonatomic, strong) SAPayRegisterDetailModel *model;
@property (nonatomic, strong) SAPayCommonUploadAPI *payCommonUploadAPI;

@property (nonatomic, strong) NSString *bankCardFrontPic;
@property (nonatomic, strong) SAPayRegisterAccountInfoAPI *payRegisterAccountInfoAPI;
@property (nonatomic, strong) SALivingBodyCheckAPI *livingBodyCheckAPI;
@property (nonatomic, strong) SAPayRegisterSubmitAuditAPI *payRegisterSubmitAuditAPI;

@end

@implementation SAAccountInfoVC

-(instancetype)initWithModel:(SAPayRegisterDetailModel *)model {
    if (self = [super init]) {
        self.model = model;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.payCommonUploadAPI == api) {
        [HDHubView dismiss];
        NSString *imgURL = data[@"data"][@"imgURL"];
        self.bankCardFrontPic = data[@"data"][@"fileId"];
        [self.cardImageV sd_setImageWithURL:[NSURL URLWithString:imgURL]];
        [self showNext];
    }else if (self.payRegisterAccountInfoAPI == api) {
        [self.payRegisterDetailAPI sendRequestToServerWithActivityViewAndMask:POST];
    }else if (self.payRegisterDetailAPI == api) {
//        self.model = [SAPayRegisterDetailModel mj_objectWithKeyValues:data[@"data"]];
//        if ([self.model.merchantDetailVO.legalInfoStatus isEqualToString:@"1"] && [self.model.merchantDetailVO.baseInfoStatus isEqualToString:@"1"] && [self.model.merchantDetailVO.accountInfoStatus isEqualToString:@"1"]) {
//            if (![QRCodePermissions allowCamera]) {
//                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请开启摄像头权限" message:@"请在\"设置 - 隐私 - 相机\"选项中，允许访问您的相机" preferredStyle:UIAlertControllerStyleAlert];
//                UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                }];
//                UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
//                }];
//                [alert addAction:action];
//                [alert addAction:action2];
//                [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
//                return;
//            }
//            NSDictionary *param = @{@"actions":@"1279", @"actionsNum":@"3"};
//            [[Liveness shareInstance] startProcess:self withParam:param withDelegate:self];
//        }else {
            [self popVC:@"SABusinessInformationVC" :YES];
//        }
    }else if (self.livingBodyCheckAPI == api) {
        NSString *score = data[@"data"][@"data"][@"score"];
        NSString *msg = data[@"data"][@"data"][@"msg"];
        if ([score floatValue] > 0.45) {
            [self.payRegisterSubmitAuditAPI sendRequestToServerWithActivityViewAndMask:POST];
        }else {
            [Prompt popPromptViewWithMsg:msg duration:3];
        }
    }else if (self.payRegisterSubmitAuditAPI == api) {
        [self popVC:@"SABusinessInformationVC" :YES];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    if (self.payCommonUploadAPI == api) {
        [HDHubView dismiss];
        [Prompt popPromptViewWithMsg:@"图片上传失败" duration:2];
    }
}

#pragma mark - LivenessDetectDelegate
- (void)onLiveDetectCompletion:(NSDictionary *)result{
    NSString *code = [result objectForKey:@"code"];
    if ([code isEqualToString:@"0"]) {
        NSString *passFace = [result objectForKey:@"passFace"];
        
        self.livingBodyCheckAPI.idCardNo = self.model.merchantLegalPersonVO.idCardNo;
        self.livingBodyCheckAPI.name = self.model.merchantLegalPersonVO.legalName;
        self.livingBodyCheckAPI.image = passFace;
        [self.livingBodyCheckAPI sendRequestToServerWithActivityViewAndMask:POST];
    }else{
        NSString *msg = [result objectForKey:@"msg"];
        [Prompt popPromptViewWithMsg:msg duration:3];
    }
}

#pragma mark - UITextFieldDelegate
- (void)textFieldEditChanged:(UITextField*)textField {
    NSString *newStr = [textField.text noEmoji];
    if (textField.text.length != newStr.length) {
        textField.text = newStr;
    }
    [self showNext];
}

-(void)clickedCardImageV {
    
    if (![QRCodePermissions allowCamera]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请开启摄像头权限" message:@"请在\"设置 - 隐私 - 相机\"选项中，允许访问您的相机" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alert addAction:action];
        [alert addAction:action2];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    __weak typeof(self) weakSelf = self;
    UIViewController * vc =
    [AipCaptureCardVC ViewControllerWithCardType:CardTypeBankCard
                                 andImageHandler:^(UIImage *image) {
        
        [[AipOcrService shardService] detectBankCardFromImage:image
                                               successHandler:^(id result){
            NSString *name = @"";
            NSString *Id = @"";
            if([result[@"result"] isKindOfClass:[NSDictionary class]]){
                name = result[@"result"][@"bank_name"];
                Id = result[@"result"][@"bank_card_number"];
            }
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                if (Id.length > 0) {
                    weakSelf.bankNumTf.text = Id;
                }
                if (name.length > 0) {
                    weakSelf.bankNameTf.text = name;
                }
                if (image) {
                    [weakSelf.payCommonUploadAPI sendServerImageData:image];
                }
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
            }];
        }
                                                  failHandler:^(NSError* err){
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                if (image) {
                    [weakSelf.payCommonUploadAPI sendServerImageData:image];
                }
                [Prompt popPromptViewWithMsg:@"识别失败，请手动输入" duration:3];
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
            }];
        }];
        
    }];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

-(void)clickedNextBtn {
    if ([self.model.merchantDetailVO.auditStatus isEqualToString:@"0"] || [self.model.merchantDetailVO.auditStatus isEqualToString:@"1"]) {
        [self popVC:@"SABusinessInformationVC" :YES];
        return;
    }
    
    self.payRegisterAccountInfoAPI.merchantId = [SAValueManger shareInStance].userInfo.merchantId;
    self.payRegisterAccountInfoAPI.holder = self.accountNameTf.text;
    self.payRegisterAccountInfoAPI.bankName = self.bankNameTf.text;
    NSString *bankCardNo = [self.bankNumTf.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    self.payRegisterAccountInfoAPI.bankCardNo = bankCardNo;
    self.payRegisterAccountInfoAPI.bankCardFrontPic = self.bankCardFrontPic;
    [self.payRegisterAccountInfoAPI sendRequestToServerWithActivityViewAndMask:POST];
}

-(void)showNext {
    BOOL isShow = YES;
    if (self.bankCardFrontPic.length == 0) {
        isShow = NO;
    }
    if (self.accountNameTf.text.length == 0) {
        isShow = NO;
    }
    if (self.bankNameTf.text.length == 0) {
        isShow = NO;
    }
    if (self.bankNumTf.text.length == 0) {
        isShow = NO;
    }

    if (isShow == YES) {
        self.nextBtn.userInteractionEnabled = YES;
        [self.nextBtn setBackgroundImage:[UIImage imageNamed:@"button_blue_bg"] forState:UIControlStateNormal];
    }else {
        self.nextBtn.userInteractionEnabled = NO;
        [self.nextBtn setBackgroundImage:[UIImage imageNamed:@"button_gray_bg"] forState:UIControlStateNormal];
    }
}

-(void)clickedWechatBtn {
    SAConsultationWechatVC *pushVC = [SAConsultationWechatVC new];
    [self.navigationController pushViewController:pushVC animated:YES];
}

-(void)initData {
    if ([self.model.merchantDetailVO.accountInfoStatus isEqualToString:@"1"]) {
        [self.cardImageV sd_setImageWithURL:[NSURL URLWithString:self.model.merchantAccountInfoVO.bankCardFrontPicUrl]];
        self.bankCardFrontPic = self.model.merchantAccountInfoVO.bankCardFrontPic;
        self.accountNameTf.text = self.model.merchantAccountInfoVO.holder;
        self.bankNameTf.text = self.model.merchantAccountInfoVO.bankName;
        self.bankNumTf.text = self.model.merchantAccountInfoVO.bankCardNo;
        [self showNext];
    }else if ([self.model.merchantDetailVO.legalInfoStatus isEqualToString:@"1"]) {
        self.accountNameTf.text = self.model.merchantLegalPersonVO.legalName;
    }
    
    if ([self.model.merchantDetailVO.auditStatus isEqualToString:@"0"] || [self.model.merchantDetailVO.auditStatus isEqualToString:@"1"]) {
        self.cardImageV.userInteractionEnabled = NO;
        self.accountNameTf.userInteractionEnabled = NO;
        self.bankNameTf.userInteractionEnabled = NO;
        self.bankNumTf.userInteractionEnabled = NO;
    }
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:@"收款卡信息"];
    self.view.backgroundColor = kLineColor;
    
    UIImageView *cardImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pay_bankCard"]];
    cardImageV.frame = SARectMake(100, StatusHeight + 30, 175, 99);
    cardImageV.userInteractionEnabled = YES;
    cardImageV.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:cardImageV];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickedCardImageV)];
    [cardImageV addGestureRecognizer:tap];
    self.cardImageV = cardImageV;
    
    UIImageView *cameraImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pay_camera2"]];
    cameraImageV.frame = SARectMake(100, StatusHeight + 30, 175, 99);
    cameraImageV.userInteractionEnabled = NO;
    cameraImageV.contentMode = UIViewContentModeCenter;
    [self.view addSubview:cameraImageV];
    
    if ([self.model.merchantDetailVO.auditStatus isEqualToString:@"0"] || [self.model.merchantDetailVO.auditStatus isEqualToString:@"1"]) {
        cameraImageV.hidden = YES;
    }
    
    UILabel *cardTitleLab = [[UILabel alloc] initWithFrame:SARectMake(0, StatusHeight + 145, kBaseScreenWidth, 20)];
    cardTitleLab.font = kFont(15);
    cardTitleLab.text = @"一类储蓄卡正面照";
    cardTitleLab.textColor = kBlackColor;
    cardTitleLab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:cardTitleLab];
    
    NSArray *arr = @[@"开户名", @"银行名称", @"银行卡号"];
    for (int i = 0; i < arr.count; i++) {
        UILabel *titleLab1 = [[UILabel alloc] initWithFrame:SARectMake(33, StatusHeight + 206 + 50 * i, 75, 35)];
        titleLab1.text = arr[i];
        titleLab1.textColor = kBlackColor;
        titleLab1.font = kFont(15);
        titleLab1.numberOfLines = 0;
        titleLab1.textAlignment = NSTextAlignmentLeft;
        [self.view addSubview:titleLab1];
        
        UITextField *textTf = [[UITextField alloc] initWithFrame:SARectMake(112, StatusHeight + 201 + 50 * i, 230, 45)];
        textTf.font = kFont(15);
        textTf.clearButtonMode = UITextFieldViewModeWhileEditing;
        [textTf addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
        textTf.delegate = self;
        [self.view addSubview:textTf];
        
        if (i == 0) {
            self.accountNameTf = textTf;
            textTf.placeholder = @"银行卡开户名身份证信息一致";
        }else if (i == 1) {
            self.bankNameTf = textTf;
            textTf.placeholder = @"请输入银行名称";
        }else if (i == 2) {
            self.bankNumTf = textTf;
            textTf.placeholder = @"请输入储蓄卡卡号";
            textTf.keyboardType = UIKeyboardTypeNumberPad;
        }
        
        UIView *line = [[UIView alloc] initWithFrame:SARectMake(33, StatusHeight + 241 + 50 * i, kBaseScreenWidth - 66, 1)];
        line.backgroundColor = kColor(200, 200, 200, 1);
        line.userInteractionEnabled = NO;
        [self.view addSubview:line];
    }
    
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [nextBtn setBackgroundImage:[UIImage imageNamed:@"button_gray_bg"] forState:UIControlStateNormal];
        nextBtn.frame = CGRectMake(kScaleNum(70), kScaleNum(StatusHeight + 369), kScaleNum(235), kScaleNum(35));
    [nextBtn setTitle:@"保存" forState:UIControlStateNormal];
    nextBtn.titleLabel.font = kFont(16);
    nextBtn.userInteractionEnabled = NO;
    [nextBtn addTarget:self action:@selector(clickedNextBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextBtn];
    self.nextBtn = nextBtn;
    
    UIButton *wechatBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    wechatBtn.frame = CGRectMake((kScreenWidth - kScaleNum(150))/2, kScaleNum(StatusHeight + 404), kScaleNum(150), kScaleNum(35));
    [wechatBtn setTitle:@"添加客服咨询>" forState:UIControlStateNormal];
    [wechatBtn setTitleColor:kBuleColor forState:UIControlStateNormal];
    wechatBtn.titleLabel.font = kFont(13);
    [wechatBtn addTarget:self action:@selector(clickedWechatBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:wechatBtn];
}

-(SAPayRegisterDetailAPI *)payRegisterDetailAPI {
    if (!_payRegisterDetailAPI) {
        _payRegisterDetailAPI = [SAPayRegisterDetailAPI apiWithDelegate:self];
    }
    return _payRegisterDetailAPI;
}

-(SAPayCommonUploadAPI *)payCommonUploadAPI {
    if (!_payCommonUploadAPI) {
        _payCommonUploadAPI = [SAPayCommonUploadAPI apiWithDelegate:self];
    }
    return _payCommonUploadAPI;
}

-(SAPayRegisterAccountInfoAPI *)payRegisterAccountInfoAPI {
    if (!_payRegisterAccountInfoAPI) {
        _payRegisterAccountInfoAPI = [SAPayRegisterAccountInfoAPI apiWithDelegate:self];
    }
    return _payRegisterAccountInfoAPI;
}

-(SALivingBodyCheckAPI *)livingBodyCheckAPI {
    if (!_livingBodyCheckAPI) {
        _livingBodyCheckAPI = [SALivingBodyCheckAPI apiWithDelegate:self];
    }
    return _livingBodyCheckAPI;
}

-(SAPayRegisterSubmitAuditAPI *)payRegisterSubmitAuditAPI {
    if (!_payRegisterSubmitAuditAPI) {
        _payRegisterSubmitAuditAPI = [SAPayRegisterSubmitAuditAPI apiWithDelegate:self];
    }
    return _payRegisterSubmitAuditAPI;
}

@end
